package com.itheima.service.impl;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.PageQuery;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.User;
import com.itheima.pojo.UserLoginVo;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult page(PageQuery<User> pageQuery) {
        User user = pageQuery.getBody();
        long total = userMapper.count(user);
        List<User> list= userMapper.list(pageQuery);
        int pages=(int) (total%pageQuery.getPageSize()==0? total/pageQuery.getPageSize():total/pageQuery.getPageSize()+1);
        PageResult pageResult = PageResult.builder()
                .currentPage(pageQuery.getPage())
                .total(total)
                .pages(pages)
                .build();
        pageResult.setData(list);
        return pageResult;
    }

    //登录
    @Override
    public UserLoginVo login(User user) {
        User userInfo= userMapper.login(user);
        if(userInfo!=null){
            UserLoginVo vo=new UserLoginVo();
            BeanUtils.copyProperties(userInfo,vo);

            Map<String,Object> payload = new HashMap<>();
            payload.put("id",userInfo.getId());
            payload.put("username",userInfo.getUsername());
            payload.put("name",userInfo.getName());
            String token = JwtUtils.generateJwt(payload);
            vo.setToken(token);
            return vo;

        }else{
            return null;
        }

    }
}
